package search

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"

	"gitee.com/Flearning/go_crawl/modules/mgobson"
	"gitee.com/Flearning/go_crawl/setting"
	"gitee.com/Flearning/go_crawl/utils/strip"
)

var MgoXueqiuCollection string
var MgoStripCollection string

//func Init(collection string) {
//	mgoXueqiuCollection = collection
//}

func RunXueqiuCount() (int, error) {
	var count int
	var err error
	query := func(c *mgo.Collection) error {
		count, err = c.Count()
		return err
	}
	err = mgobson.WatchCollection(MgoXueqiuCollection, query)
	return count, err
}

func RunXueqiuInstert(v ...interface{}) error {
	query := func(c *mgo.Collection) error {
		return c.Insert(v...)
	}
	return mgobson.WatchCollection(MgoXueqiuCollection, query)
}

func ReadMgoCfg() *setting.MgoInfo {
	return setting.InfoMgo
}

func RunXueqiuCheck(where []bson.M) (bool, error) {
	var check bool
	var count int
	var err error
	query := func(c *mgo.Collection) error {
		wheres := bson.M{
			"$and": where,
		}
		count, err = c.Find(wheres).Count()
		return err
	}
	err = mgobson.WatchCollection(MgoXueqiuCollection, query)
	if err != nil {
		return check, err
	}
	if count > 0 {
		check = true
	}
	return check, err
}

func RunStripDataInstert(res ...ListStruct) error {
	newRes := make([]interface{}, 0)
	for key, val := range res {
		res[key].Description = stripTagsData(val.Description)
		res[key].Text = stripTagsData(val.Text)
		newRes = append(newRes, res[key])
	}
	query := func(c *mgo.Collection) error {
		return c.Insert(newRes...)
	}
	return mgobson.WatchCollection(MgoStripCollection, query)
}

func stripTagsData(str string) string {
	return strip.StripTags(str)
}
